package com.itany.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.cms.constant.DictConstant;
import com.itany.cms.constant.StatusConstant;
import com.itany.cms.dao.ChapterMapper;
import com.itany.cms.dao.CommentMapper;
import com.itany.cms.dao.ResourceMapper;
import com.itany.cms.entity.*;

import com.itany.cms.exception.CourseExistException;
import com.itany.cms.exception.FileUploadErrorException;
import com.itany.cms.exception.RequestParameterErrorException;
import com.itany.cms.service.ChapterService;
import com.itany.cms.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ChapterServiceImpl implements ChapterService {
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private CommentMapper commentMapper;

    public ChapterServiceImpl(ChapterMapper chapterMapper) {
        this.chapterMapper = chapterMapper;
    }

    @Override
    public PageInfo<Chapter> findByParams(Chapter chapterParam, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.CHAPTER_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.CHAPTER_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        if (!ParameterUtil.isNull(chapterParam.getTitle())) {
            wrapper.like("title", chapterParam.getTitle());
        }
        if (!ParameterUtil.isNull(chapterParam.getInfo())) {
            wrapper.like("info", chapterParam.getInfo());
        }
        if (!ParameterUtil.isNull(chapterParam.getStartCreateDate())||!ParameterUtil.isNull(chapterParam.getStartCreateDate())) {
            wrapper.between("create_date", chapterParam.getStartCreateDate(),chapterParam.getEndCreateDate());
        }
        if (!ParameterUtil.isNull(chapterParam.getStatus())) {
            wrapper.eq("status", chapterParam.getStatus());
        }if (!ParameterUtil.isNull(chapterParam.getCourseId())) {
            wrapper.eq("course_id", chapterParam.getCourseId());
        }
        List<Chapter> chapters = chapterMapper.selectList(wrapper);
        PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chapters);
        return chapterPageInfo;
    }

    @Override
    public PageInfo<Chapter> findChapter(Chapter chapterParam, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.CHAPTER_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.CHAPTER_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",chapterParam.getCourseId());
        List<Chapter> chapters = chapterMapper.selectList(wrapper);
        PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chapters);
        return chapterPageInfo;
    }

    @Override
    public PageInfo<Comment> findComment(String id, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.CHAPTER_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.CHAPTER_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",Integer.parseInt(id));
        List<Resource> resources = resourceMapper.selectList(wrapper);
        QueryWrapper<Comment> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("resource_id",resources.get(0).getId());
        List<Comment> comments = commentMapper.selectList(wrapper1);
        PageInfo<Comment> commentPageInfo = new PageInfo<>(comments);
        return commentPageInfo;
    }

    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id) || ParameterUtil.isNull(status)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Chapter chapter = new Chapter();
        chapter.setId(Integer.parseInt(id));
        chapter.setStatus(Integer.parseInt(status));
        if (chapter.getStatus() == StatusConstant.CHAPTER_STATUS_ENABLED) {
            chapter.setStatus(StatusConstant.CHAPTER_STATUS_DISABLED);
        } else {
            chapter.setStatus(StatusConstant.CHAPTER_STATUS_ENABLED);
        }
        chapterMapper.updateById(chapter);

    }

    @Override
    public void addChapter(String courseId, String title, String info, MultipartFile file, String resourceTitle, String costType, String costNumber, String fileType) throws RequestParameterErrorException, FileUploadErrorException {
        if (ParameterUtil.isNull(courseId) ||ParameterUtil.isNull(title) || ParameterUtil.isNull(info) || ParameterUtil.isNull(resourceTitle) || file.isEmpty() || ParameterUtil.isNull(costType)|| ParameterUtil.isNull(costNumber)|| ParameterUtil.isNull(fileType)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Chapter chapter = new Chapter();
        chapter.setCourseId(Integer.parseInt(courseId));
        chapter.setTitle(title);
        chapter.setInfo(info);
        chapter.setStatus(StatusConstant.CHAPTER_STATUS_ENABLED);
        Resource resource = new Resource();
        resource.setTitle(resourceTitle);
        resource.setCostType(Integer.parseInt(costType));
        resource.setCostNumber(Integer.parseInt(costNumber));
        resource.setFileType(fileType);
        try { // 上传商品图片
            // 指定相对路径
            String path = DictConstant.RESOURCE_IMAGE_ROOT_FOLDER + new SimpleDateFormat("yyyyMMdd").format(new Date());
            // 获取绝对路径
//        String cp = session.getServletContext().getRealPath(path);
            String cp = ResourceUtils.getURL("classpath:").getPath() + path;
            System.out.println("***************当前课程图片的路径为:" + cp);
            // 创建目录
            File f = new File(cp);
            f.mkdirs();

            // 生成商品图片属性值
            resource.setPath(path + "/" + file.getOriginalFilename());
            // 添加商品
            resourceMapper.insert(resource);
            // 上传图片
            file.transferTo(new File(cp, file.getOriginalFilename()));
        } catch (IOException e) {
            throw new FileUploadErrorException("课程图片上传失败");
        }
    }


    @Override
    public void modifyChapter(String id, String name, String author, MultipartFile file, String recommendationGrade, String courseTypeId) {

    }
}
